/**
 * @Project Name:life-login-service
 * @Package Name:cn.hoofungson.life.login.service.advice.handler
 * @Since JDK 1.8
 */

package cn.hoofungson.blog.login.api.advice.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.client.HttpClientErrorException;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Description:
 * @Author 胡松 hoofungson@163.com
 * @Date 2020-02-14 18:44
 * @Version V1.0
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕获参数异常
     **/
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public HttpEntity<Map<String, Object>> missingServletRequestParameterException(MissingServletRequestParameterException exception) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("code", 400101);
        map.put("message", "请求参数异常：" + exception.getMessage());
        log.error("捕获全局异常请求参数异常：", exception);
        return new HttpEntity<>(map);
    }

    /**
     * 捕获认证异常
     **/
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(HttpClientErrorException.class)
    public HttpEntity<Map<String, Object>> httpClientErrorException(HttpClientErrorException exception) {
        Map<String, Object> map = new LinkedHashMap<>();
        if (exception instanceof HttpClientErrorException.Unauthorized) {
            map.put("code", 400102);
            map.put("message", "用户名输入有误！");
        }
        if (exception instanceof HttpClientErrorException.BadRequest) {
            map.put("code", 400103);
            map.put("message", "密码输入有误！");
        }
        log.warn("捕获全局异常登录校验异常：", exception.getMessage());
        return new HttpEntity<>(map);
    }
}
